package msg

import (
	"context"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	uuid "github.com/satori/go.uuid"
	"go-zero-project/services/user/api/constans"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DelayMsgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDelayMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelayMsgLogic {
	return &DelayMsgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DelayMsgLogic) DelayMsg(req *types.SendDelayMsgReq) (resp *types.SendDelayMsgResp, err error) {
	// covert request
	bodyByte := []byte(req.Msg)
	message := primitive.Message{Topic: constans.UserDelayTopic, Body: bodyByte}
	message.WithTag("delay")
	message.WithKeys([]string{uuid.NewV4().String()})
	message.WithDelayTimeLevel(3)
	// send msg
	sendResult, err := l.svcCtx.DefaultProducer.SendSync(l.ctx, &message)
	if err != nil {
		return nil, err
	}
	logx.Infof("msgId %s,topic:%s,send msg:%s!", message.Topic,
		sendResult.MsgID, string(message.Body))
	// return obj
	return &types.SendDelayMsgResp{Topic: constans.UserDelayTopic,
		Msg: string(bodyByte)}, nil
}
